package edu.uic.ids517;

import java.sql.SQLException;
import java.util.Map;

import javax.faces.context.FacesContext;

public class ActionBeanLoginLogout {

	ActionBeanDbaseAccess dbaseBean;
	MessageBean messageBean;

	public MessageBean getMessageBean() {
		return messageBean;
	}

	public void setMessageBean(MessageBean messageBean) {
		this.messageBean = messageBean;
	}

	public ActionBeanDbaseAccess getDbaseBean() {
		return dbaseBean;
	}

	public void setDbaseBean(ActionBeanDbaseAccess dbaseBean) {
		this.dbaseBean = dbaseBean;
	}

	public String processLogin(){
		if(dbaseBean.openConnection()){
			messageBean.setErrorMessage(false);
			messageBean.setMessage("");
			
			return "SUCCESS";
			
		}
		else return "FAIL";
	}

	public String processLogout() throws SQLException {

		boolean connectStatus = dbaseBean.closeConnection();

		FacesContext context = FacesContext.getCurrentInstance();
		Map <String, Object> m = context.getExternalContext().getSessionMap();
		dbaseBean = (ActionBeanDbaseAccess) m.get("dbaseBean");

		if(connectStatus) {
			dbaseBean.closeConnection();
		}
		
		context.getExternalContext().invalidateSession();
		return "SUCCESS";

	}
	public String registerUser(){
		System.out.println("inside ABLL: registerUser() ");

		try {
			if(dbaseBean.registerUser())
				return "SUCCESS";

		} catch (SQLException e) {
			System.out.println("Registration Failure");
			//e.printStackTrace();
		}
		return "FAIL";
	}

	public String validateUser(){
		try {
			return dbaseBean.validateUser();

		} catch (SQLException e) {
			System.out.println("Login Failure");
			//e.printStackTrace();
		}
		return "invalid";
	}


}
